import React, { Component } from 'react';
import { Table, Pagination, Message, Dialog, Button, Balloon, Grid, Dropdown, Menu } from '@alifd/next';
import IceContainer from '@icedesign/container';
import TableFilter from './TableFilter';
import EditForm from '../EditForm';
import { ApiOfPolicyPage, ApiOfPolicyEnable, ApiOfPolicyDisable, ApiOfPolicyDelete } from '#/utils/policyApiDefine'
import SearchTableWrapper from '#/hoc/SearchTableWrapper';
import BindResource from '../BindResource';
import BindLinkage from '../BindLinkage';
import BindExpression from '../BindExpression';

const { Row, Col } = Grid;
@SearchTableWrapper(ApiOfPolicyPage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      detailDialogVisible: false,
      bindResourceDialogVisible: false,
      bindExpressionDialogVisible: false,
      bindLinkageDialogVisible: false,
      editInstance: {},
    };
  }
  onDeleteConfirmOk = item => {
    return ApiOfPolicyDelete(item.code)
  }
  onToggleStatusConfirm = (item) => {
    let that = this;
    let Api = item.disabled ? ApiOfPolicyEnable : ApiOfPolicyDisable
    Dialog.confirm({
      title: '',
      content: '确认要' + (item.disabled ? '开启' : '禁用') + '吗?',
      onOk: () => {
        Api(item.code).then(response => {
          that.props.fetch();
          Message.success('操作成功!');
        }).catch(function (error) {
          console.log(error);
        });
      }
    });
  }
  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }
  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }
  onOpenResBindDialog = item => {
    this.setState({
      bindResourceDialogVisible: true,
      editInstance: item
    });
  }
  onOpenExpBindDialog = item => {
    this.setState({
      bindExpressionDialogVisible: true,
      editInstance: item
    });
  }
  onCloseResBindDialog = reason => {
    this.setState({
      bindResourceDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }
  onCloseExpBindDialog = reason => {
    this.setState({
      bindExpressionDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }
  onOpenLinkageBindDialog = item => {
    this.setState({
      bindLinkageDialogVisible: true,
      editInstance: item
    });
  }
  onCloseLindageBindDialog = reason => {
    this.setState({
      bindLinkageDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }
  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    let that = this;
    return (
      <div>
        <Dropdown align="tr br" trigger={<Button style={{ 'width': '120px' }}>操作列表</Button>} triggerType={"hover"} afterOpen={() => console.log('after open')}>
          <Menu>
            <Menu.Item><Button onClick={() => this.onToggleStatusConfirm(item)} type="primary" text style={{ color: (item.disabled) ? '#ff3000' : '#2874D1' }}>{item.disabled ? '启用' : '禁用'}</Button></Menu.Item>
            <Menu.Item><Button onClick={() => this.onOpenDetailDialog(item)} type="primary" text>编辑</Button></Menu.Item>
            <Menu.Item><Button onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text>删除</Button></Menu.Item>
            <Menu.Item><Button onClick={() => this.onOpenResBindDialog(item)} type="primary" text>资源({item.policyRefResources.length})</Button></Menu.Item>
            <Menu.Item><Button onClick={() => this.onOpenExpBindDialog(item)} type="primary" text>表达式({item.expressions.length})</Button></Menu.Item>
            <Menu.Item><Button onClick={() => this.onOpenLinkageBindDialog(item)} type="primary" text>联动</Button></Menu.Item>
          </Menu>
        </Dropdown>
      </div>
    );
  }

  renderPolicyType = (value, index, item) => {
    let policyType = item.policyType;
    if (policyType === 'SYSTEM') {
      policyType = '系统告警';
    } else if (policyType === 'DEVICE_FAULT') {
      policyType = '设备故障告警';
    } else if (policyType === 'GATEWAY_DISCONNECT') {
      policyType = '通讯中断告警';
    } else if (policyType === 'POLICY_ALARM') {
      policyType = '策略告警';
    } else if (policyType === 'POLICY_COMPLEX') {
      policyType = '复杂策略告警';
    } else if (policyType === 'SUB_SYSTEM_ALARM') {
      policyType = '子系统告警';
    }
    return (
      <span>{policyType}</span>
    );
  }

  renderStatus = (value, index, item) => {
    return (
      <span>{item.disabled ? '已停用' : '已启用'}</span>
    );
  }
  onOpenBindDialog = item => {
    this.setState({
      bindDialogVisible: true,
      editInstance: item
    });
  }

  render() {
    const { instances } = this.props.bindingData;
    return (
      <IceContainer style={this.props.styles.container} >
        <TableFilter
          filter={this.props.filter}
          match={this.props.match}
        />
        <Row wrap gutter="20" style={styles.formRow}>
          <Col l="8">
            <Button onClick={() => this.onOpenDetailDialog()} size="small" type="primary">
              创建
            </Button>
          </Col>
          <Col l="16">
            <Pagination
              style={this.props.styles.pagination}
              shape="arrow-only"
              pageSizeSelector="filter"
              current={this.props.page}
              total={instances.pageable.totalElements}
              totalRender={total => `总数: ${total}`}
              pageSize={instances.pageable.size}
              onChange={this.props.handlePaginationChange}
              onPageSizeChange={this.props.handlePageSizeChange}
            />
          </Col>
        </Row>
        <Table
          dataSource={instances.data}
          loading={this.props.loading}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
          onSort={this.props.handleSort}
        >
          <Table.Column width={150} title="名称" dataIndex="name" sortable={true} />
          <Table.Column width={150} title="编码" dataIndex="code" />
          <Table.Column width={180} title="描述" dataIndex="description" />
          <Table.Column width={100} title="执行频次" dataIndex="criterion" />
          <Table.Column width={120} title="事件类型" dataIndex="policyType" cell={this.renderPolicyType} />
          <Table.Column title="事件内容" dataIndex="contentTemplate" />
          <Table.Column
            width={80}
            title="状态"
            dataIndex="disabled"
            cell={this.renderStatus}
            sortable={true} />
          <Table.Column
            width={140}
            title="操作"
            cell={this.renderOper}
          />
        </Table>
        <Pagination
          style={this.props.styles.pagination}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Dialog
          style={{ width: '50%' }}
          title="编辑策略信息"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>
        <Dialog
          className="dialog-with-table"
          style={{ width: '80%' }}
          title="关联资源"
          visible={this.state.bindResourceDialogVisible}
          footer={false}
          onClose={this.onCloseResBindDialog}>
          <BindResource editInstance={this.state.editInstance} match={this.props.match} submitCallback={this.onCloseResBindDialog} />
        </Dialog>
        <Dialog
          className="dialog-with-table"
          style={{ width: '80%' }}
          title="联动资源"
          visible={this.state.bindLinkageDialogVisible}
          footer={false}
          onClose={this.onCloseLindageBindDialog}>
          <BindLinkage editInstance={this.state.editInstance} match={this.props.match} submitCallback={this.onCloseLindageBindDialog} />
        </Dialog>
        <Dialog
          className="dialog-with-table"
          style={{ width: '80%' }}
          title="关联表达式"
          visible={this.state.bindExpressionDialogVisible}
          footer={false}
          onClose={this.onCloseExpBindDialog}>
          <BindExpression editInstance={this.state.editInstance} match={this.props.match} submitCallback={this.onCloseExpBindDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
};
